package com.clgc.eduservice.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.clgc.baseservice.exception.MyException;
import com.clgc.eduservice.entity.EduTeacher;
import com.clgc.eduservice.entity.TeacherLoginEntity;
import com.clgc.eduservice.entity.excel.TeacherExcel;
import com.clgc.eduservice.listener.TeacherListener;
import com.clgc.eduservice.service.EduTeacherService;
import com.clgc.utils.MD5Utils;
import com.clgc.utils.R;
import com.clgc.utils.ResultCode;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.HEAD;
import java.io.IOException;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 老师表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2021-04-27
 */
@RestController
@RequestMapping("/eduservice/edu-teacher")
public class EduTeacherController {
    @Autowired
    private EduTeacherService eduTeacherService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private TeacherListener teacherListener;

    @GetMapping("/teacher/{id}")
    public R getTeacher(@PathVariable Integer id) {
        EduTeacher teacher = eduTeacherService.getById(id);
        if (teacher == null) {
            return R.error().message("查询老师信息失败");
        }
        return R.ok().data("data", teacher);
    }

    @ApiOperation("查询所有老师")
    @GetMapping("/getAllTeacher")
    public R getAllTeacher() {
        List<EduTeacher> list = eduTeacherService.list(null);
        return R.ok().data("list", list);
    }

    @ApiOperation(value = "获取当前老师登录的所有信息")
    @GetMapping("/teacher/info")
    public EduTeacher getTeacherInfo(Principal principal) {
        System.out.println("-------------getTeacherInfoController---------------");
        System.out.println("security getUsername------------>" + SecurityContextHolder.getContext().getAuthentication().getName());
        System.out.println("principal-------------->" + principal);
        if (principal == null) {
            return null;
        }
        String username = principal.getName();
        System.out.println("principal username---------------->" + username);
        EduTeacher teacher = eduTeacherService.getTeacherByUsername(username);
        //密码不可见
        teacher.setPwd(null);
        return teacher;
    }

    @ApiOperation("老师注册批量入库（通过手动输入）")
    @PostMapping("/teacherRegisterByList")
    public R teacherRegisterByList(@RequestBody List<EduTeacher> teacherList) {
        for (EduTeacher eduTeacher : teacherList) {
            String pwd = eduTeacher.getPwd();
            String md5Encode = MD5Utils.MD5Encode(pwd);
            eduTeacher.setPwd(md5Encode);
        }
        boolean flag = eduTeacherService.saveBatch(teacherList);
        return flag ? R.ok().message("导入成功") : R.error().message("导入失败");
    }


    @ApiOperation("老师批量入库（excel表）")
    @PostMapping("/teacherRegisterByExcel")
    public R teacherRegisterByExcel(MultipartFile multipartFile) {
        try {
            EasyExcel.read(multipartFile.getInputStream(), TeacherExcel.class, teacherListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("老师批量导入失败", ResultCode.ERROR);
        }
        return R.ok().message("导入成功");

    }

    @ApiOperation("登录")
    @PostMapping("/teacherLogin")
    public R teacherLogin(@RequestBody TeacherLoginEntity teacherLoginEntity, HttpServletRequest request) {
        return eduTeacherService.login(teacherLoginEntity.getUsername(), teacherLoginEntity.getPwd(), request);
    }

    @ApiOperation(value = "注销")
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        String authHeader = request.getHeader(tokenHeader);
        HashMap<String, Object> tokenMap = new HashMap<>();
        if (null != tokenHeader) {
            String token = authHeader.substring(tokenHead.length()) + 1;
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
        }
        return R.ok().message("注销成功").data(tokenMap);
    }

    @ApiOperation(value = "更新当前用户信息")
    @PostMapping("/updateInfo")
    public R updateStudentInfo(@RequestBody EduTeacher eduTeacher, HttpServletRequest request) {
        String pwd = eduTeacher.getPwd();
        HashMap<String, Object> tokenMap = new HashMap<>();
        if (null != pwd) {
            String md5Pwd = MD5Utils.MD5Encode(pwd);
            eduTeacher.setPwd(md5Pwd);
            //如果密码被修改，强制退出登录
            String tokenHeader = request.getHeader(this.tokenHeader);
            String token = tokenHeader.substring(tokenHead.length()) + 1;
            tokenMap.put("token", token);
            tokenMap.put("tokenHead", tokenHead);
        }
        boolean flag = eduTeacherService.updateById(eduTeacher);
        return flag ? R.ok().message("修改成功").data(tokenMap) : R.error().message("修改失败");
    }

    @PostMapping("/userinfo")
    public R updateUserInfo(@RequestBody EduTeacher eduTeacher) {
        eduTeacher.setPwd(null);
        boolean flag = eduTeacherService.update(eduTeacher, new QueryWrapper<EduTeacher>().eq("id", eduTeacher.getId()));
        return flag ? R.ok() : R.error().message("用户信息修改失败");
    }
}

